<?php

namespace app\admin\model\cms;

use app\admin\model\User;
use app\admin\model\UserGroup;
use app\common\model\Config;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

class OrderModel extends Model
{

    // 表名
    protected $name = 'order';

    //软删除
    use SoftDelete;

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'datetime';
    //自动写入时间戳的格式
    protected $dateFormat = 'Y-m-d H:i:s';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        "pay_type_name",
        "pay_status_name",
        "goods_type_name",
        "table_name_text",
        "membership_duration_text",
        "goods_name",
        "user_nickname",
        "createtime",
        "updatetime",
        "period_validity",
    ];

    //table_name字段
    const TableName = [
        'plate'=>'论坛-板块表',
        'plate_post'=>'论坛-帖子表',
        'plaza_category'=>'广场-板块表',
        'plaza_post'=>'广场-帖子表',
        'live_category'=>'直播分类表',
        'live'=>'直播列表',
        'video'=>'投研视频-音视频表',
        'video_category'=>'投研视频-分类表',
        'user_group'=>'会员分组-会员分组表',
        'album'=>'专辑表',
        'chart_parent'=>'量化辅助分类',
        'pro_diyform'=>'量化辅助内容',
        'investment_category'=>'数据库分类',
    ];

    //有效期,只有支付成功的订单右,没支付的就是空string
    public function getPeriodValidityAttr($value, $data)
    {
        $res = '';
        //订单支付状态|默认0:未支付,1:已支付
        if ($data['pay_status'] == 1){
            if ($data['membership_duration'] == 0){
                return '永久';
            }
            // 将字符串转换为时间戳
            $timestampA = strtotime($data['pay_time']);
// 计算 $b 天后的时间戳
            $timestampC = $timestampA + ($data['membership_duration'] * 24 * 60 * 60); // 1天 = 24小时 * 60分钟 * 60秒
            // 将时间戳转换为日期格式
            $start_date = date('Y-m-d',strtotime($data['pay_time']));
            $end_date = date('Y-m-d', $timestampC);
            //$res = "{$start_date}-$end_date";
            $res = "$end_date";
        }
        return $res;
    }

    //用户昵称
    public function getUserNicknameAttr($value, $data)
    {

        $value = $value ? $value : User::where('id',$data['user_id'])->value('nickname');
        return $value;
    }

    public function getTableNameTextAttr($value, $data)
    {
        $table_name_text = '';
        switch ($data['table_name']) {
            case 'plate':
                $table_name_text = '债市论坛板块';
                break;
            case 'plate_post':
                $table_name_text = '债市论坛内容';
                break;
            case 'plaza_category':
                $table_name_text = '首页广场板块';
                break;
            case 'plaza_post':
                $table_name_text = '首页广场内容';
                break;
            case 'live_category':
                $table_name_text = '直播板块';
                break;
            case 'live':
                $table_name_text = '直播内容';
                break;
            case 'video_category':
                $table_name_text = '成长计划板块';
                break;
            case 'video':
                $table_name_text = '成长计划内容';
                break;
            case 'user_group':
                $table_name_text = '会员分组';
                break;
            case 'album':
                $table_name_text = '成长计划专辑';
                break;
            case 'chart_parent':
                $table_name_text = '量化辅助分类';
                break;
            case 'pro_diyform':
                $table_name_text = '量化辅助内容';
                break;
            case 'investment_category':
                $table_name_text = '数据库分类';
                break;
        }
        return $table_name_text;
    }

    public function getMembershipDurationTextAttr($value, $data)
    {
        $res = $data['membership_duration'] ? :'无限天';
        return $res;
    }

    public function getCreatetimeAttr($value, $data)
    {
        return $data['createtime'] ?: null;
    }

    public function getUpdatetimeAttr($value, $data)
    {
        return $data['updatetime'] ?: null;
    }

    //商品名称
    public function getGoodsNameAttr($value, $data)
    {
        $table_name = $data['table_name'];
        $goods_id = $data['goods_id'];
        switch ($table_name){
            case in_array($table_name,['plaza_category','video_category','live_category','plate','investment_category']):
                $name = Db::name($table_name)->where('id',$goods_id)->value('platename');
                break;
            case in_array($table_name,['plate_post','plaza_post']):
                $name = Db::name($table_name)->where('id',$goods_id)->value('postname');
                break;
            case in_array($table_name,['live','video']):
                $name = Db::name($table_name)->where('id',$goods_id)->value('title');
                break;
            case in_array($table_name,['user_group','album','chart_parent','pro_diyform']):
                $name = Db::name($table_name)->where('id',$goods_id)->value('name');
                break;
        }

        return !empty($name) ? $name:'';
    }

    //转换支付类型名称
    public function getPayTypeNameAttr($value, $data)
    {
        $value = $value ? $value : $data['goods_type'];
        switch ($value){
            case '1':
                $name = '微信扫码支付';
                break;
            case '2':
                $name = '积分支付';
                break;
            case '3':
                $name = '积分支付';
                break;
            case '4':
                $name = '管理员后台发放';
                break;
            case '5':
                $name = '微信小程序支付';
                break;
            default:
                $name = '';
        }
        return !empty($name) ? $name:'';
    }


    public function getGoodsTypeNameAttr($value, $data)
    {
        $value = $value ? $value : $data['goods_type'];
        switch ($value){
            case 'categories':
                 $name = '栏目';
                break;
            case 'articles':
                 $name = '文章';
                break;
            case 'user_group':
                 $name = '用户组';
                break;
            case 'album':
                 $name = '专辑';
                break;
            default:
                $name = '文章';
        }
        return !empty($name) ? $name:'';
    }

    //获取支付状态中文名称
    public function getPayStatusNameAttr($value, $data)
    {
        $value = $value ? $value : $data['pay_status'];
        if (!$value){
            $name = '未支付';
        }else{
            $name = '已支付';
        }
        return !empty($name) ? $name:'未支付';
    }

    public function user()
    {
        return $this->belongsTo("app\common\model\User", "user_id", "id", [], "LEFT")->field('id,nickname,avatar,bio,email')->setEagerlyType(1);
    }


    //支付临时申请订单
    public function payOrder_3($order_id,$user,$pay_status){
        $res = [
          'code'=>500,
          'msg'=>'',
        ];
        //pay_type支付方式|1:微信,2:积分,3:临时申请订单(不用付费,只要后台管理员同意就行)
        $order = OrderModel::where('id',$order_id)
            ->where('user_id',$user['id'])
            ->where('pay_type',3)//支付方式|1:微信,2:积分,3:临时申请订单
            ->find();
        if(!$order){
            $res['msg'] = '订单信息不正确';
            return $res;
        }

        //订单已经支付 pay_status=0:尚未支付
        if ($order['pay_status'] == 1){
            $res['msg'] = '订单已支付,请勿重复支付';
            return $res;
        }

        Db::startTrans();
        try {
            //更新订单状态
            $update_order = OrderModel::where('id',$order['id'])->update([
                'pay_status' => 1,//订单支付状态|默认0:未支付,1:已支付
                'pay_time' => date('Y-m-d H:i:s'),//用户付款时间
                'pay_num' => '',//第三方订单号
                'cash_fee' => 0,//用户实际支付金额(现金支付金额) 临时申请订单不用付款
                'is_ratify' => 1,//用户实际支付金额(现金支付金额) 临时申请订单不用付款
            ]);
            if (!$update_order){
                Db::rollback();
                $res['msg'] = '操作失败1';
                return $res;
            }
            $time = time();
            $days = 15; // 会员申请有效天数-固定15天
            //判断是否购买的是会员组
            if ($order['goods_type'] == 'user_group'){
                $user_group = UserGroup::where('id',$order['goods_id'])->find();
                //判断会员分组的有效时长 0:无限天
                if ($user_group['membership_expiry'] == 0){
                    $period_of_validity = 1;//有效期|1=长期有效,0=无效,毫秒时间戳=有效时间
                }else{
                    //看当前会员是否过期 1=长期有效,0=无效,毫秒时间戳=有效时间
                    if ($user['period_of_validity'] > 1 || !$user['period_of_validity']){
                        if ($user['period_of_validity'] < time()){
                            $user['period_of_validity'] = 0;//毫秒
                        }
                        // 计算指定天数后的时间戳 秒
                        $specifiedTimestamp = strtotime("+{$days} days", ($user['period_of_validity'] / 1000) > 0 ? : $time) * 1000;//毫秒

                        $period_of_validity = $user['period_of_validity'] + $specifiedTimestamp;//单位毫秒
                    }elseif($user['period_of_validity'] == 1){
                        $period_of_validity = 1;//会员有效期(到期时间)|1=长期有效,0=无效,毫秒时间戳=有效时间
                    }
                }

                $user_success = \app\admin\model\User::where('id',$order['user_id'])->update([
                    'group_id'=>$order['goods_id'],//会员组别id
                    'member_type'=>'member',//会员类型|tourist=游客,TrialMember=试用会员，member=正式会员'
                    'member_make_time'=>time(),//会员开通时间
                    'period_of_validity'=>$period_of_validity,//会员有效期(到期时间)|1=长期有效,0=无效,毫秒时间戳(13位)=有效时间
                ]);
                if (!$user_success){
                    Db::rollback();
                    $res['msg'] = '操作失败2';
                    return $res;
                    //dd("{user表id={$order['user_id']}微信回调成功,但更应用户信息失败" , 'error');//记录日志
                }
            }else{
                //购买分类/文章内容
                $membership_Expiry_record_model = MembershipExpiryRecordModel::where('user_id',$order['user_id'])
                    ->where('goods_type',$order['goods_type'])
                    ->where('table_name',$order['table_name'])
                    ->where('goods_id',$order['goods_id'])
                    ->order('id','desc')
                    ->find();
                //判断之前是否购买过
                $expiration_time = 0;//剩余时长|没买过就默认为0
                if ($membership_Expiry_record_model){
                    //是,时间叠加
                    $expiration_time = $membership_Expiry_record_model['expiration_time'] - $time;
                    if ($expiration_time <= 0){
                        $expiration_time = 0;
                    }
                }
                //获取订单所购买的会员时长(天)|0:无限天
                $old_membership_duration = $days * 24 * 60 *60 + $time;
//                创建
                $data_2 = [
                    'user_id'=>$order['user_id'],
                    'order_id'=>$order['id'],
                    'goods_type'=>$order['goods_type'],
                    'table_name'=>$order['table_name'],
                    'goods_id'=>$order['goods_id'],
                    'membership_duration'=>$days,
                    'expiration_time'=>$expiration_time + $old_membership_duration,
                ];
                $success_2 = MembershipExpiryRecordModel::create($data_2);//创建会员过期记录表,查询数据的时候每次获取最后一条
                if (!$success_2){
                    Db::rollback();
                    $res['msg'] = '操作失败3';
                    return $res;
                    //dd("{membership_expiry_record表order_id={$order['id']}在微信支付成功回调中创建失败" , 'error');//记录日志
                }
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $res['msg'] = '操作失败4';
            return $res;
        }
        $res['code'] = 200;
        $res['msg'] = '操作成功';
        return $res;
    }
    

    







}
